package com.pansoft.xbrl.xbrljson.util;


import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;

/**
 * <p>Title: XBPL</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2010</p>
 *
 * <p>Company: Pansoft</p>
 *
 * @author hufeng
 * @version 1.0
 */
public class NumberUtil {
    public static final int NUMBER_DDY = 0;
    public static final int NUMBER_BDY = 1;
    public static final int NUMBER_DY = 2;
    public static final int NUMBER_DYDY = 3;
    public static final int NUMBER_XY = 4;
    public static final int NUMBER_XYDY = 5;
    
    /**
     * 长度为50的字符0的字符串
     */
    public static final String	ZERO_50 = "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
    
    /**
     * 默认转换的浮点数的小数位数
     */
    private static int			_defaultDecimals = 8;
    /**
     * 默认格式化浮点数为字符串时的格式
     */
    private static String		_defaultFloatFmt = "%1$.8f";
    /**
     * 获取默认的小数位数
     * @return
     */
    public static int getDefaultDecimals(){
    	return _defaultDecimals;
    }
    /**
     * 设置默认的小数位数
     * @param dec
     */
    public static void setDefaultDecimals(int dec){
    	if( _defaultDecimals == dec) return;
    	_defaultDecimals = dec;
    	_defaultFloatFmt = "%1$. " + _defaultDecimals +"f";
    }
    public NumberUtil() {
    }

    public static int CmpDouble(double d1, double d2, int dec) {
        long l1, l2, l3 = 1;
        if (dec == 0) {
            l3 = 1;
        } else {
            for (int i = 1; i <= dec; i++) {
                l3 = l3 * 10;
            }
        }
        l1 = (long) (d1 * l3);
        l2 = (long) (d2 * l3);
        if (l1 == l2)return NUMBER_DDY;
        if (l1 != l2)return NUMBER_BDY;
        if (l1 > l2)return NUMBER_DY;
        if (l1 >= l2)return NUMBER_DYDY;
        if (l1 < l2)return NUMBER_XY;
        if (l1 <= l2)return NUMBER_XYDY;
        return -1;
    }

    /**
     * 判断浮点数是否相等
     * @param d1 double
     * @param d2 double
     * @param dec int
     * @return boolean
     */
    public static boolean equals(double d1, double d2, int dec) {
        return CmpDouble(d1, d2, dec) == NUMBER_DDY;
    }

    /**
     * 返回指定位数的 数值型数据 ,取精度
     * 取精度时需要用字符串来构造，否则会有问题
     * @param anumber double
     * @param place int
     * @return double
     */
    public static double round(double anumber, int place) {
        String sValue = String.valueOf(anumber);
        BigDecimal bigValue = new BigDecimal(sValue);
        return bigValue.setScale(place, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

//    /**
//	 * 格式化字串上，去掉小数后面的0
//	 * @param d
//	 * @param dec
//	 * @return
//	 */
//	public static String getNoTailZeroString(double d, String dec)
//	{
//		// 先这样处理，以后要考虑小数位数的问题
//		String ret = String.format("%1$f", d);
//		if( ret.indexOf('.') >= 0 )
//		{
//			int len = ret.length() -1;
//			while( ret.charAt(len) == '0')
//			{
//				len --;
//			}
//			if( ret.charAt(len) == '.')
//			{
//				len --;
//			}
//			ret = ret.substring(0, len + 1);
//		}
//		return ret;
//	}

	public static String getFormatString(double d, String dec){

		String	val	=	getNoTailZeroString(d,dec);
		if(val.equals("")){
			return "";
		}
		
		double num	=	Double.valueOf(val);

		int decimals = 0;
		if (dec != null && dec.trim().length() > 0 && !dec.equals("0") && !dec.equals("INF")) {
			decimals = Integer.parseInt(dec);
		} else if (dec != null && (dec.equals("INF") || dec.equals("0"))){
			double number = Double.parseDouble(getNoTailZeroString(d,dec));
			DecimalFormat df = (DecimalFormat)DecimalFormat.getInstance();
			df.setMaximumFractionDigits(100);
			df.setGroupingSize(3);
			return df.format(number);
		} else {
			return new Double(num).toString();
		}
	
		double number	=	0;
		if(decimals < 0){
			number	=	num * Math.pow(10,decimals);
		}else{
			number	= 	num;
		}
		
		NumberFormat nf = NumberFormat.getInstance();
		int scale	=	0;
		if(decimals > 0){
			scale	=	decimals;
			nf.setMinimumFractionDigits(scale);
		}
		return nf.format(new BigDecimal(number).setScale(scale, BigDecimal.ROUND_HALF_DOWN));
	}
	//==================================
    /**
	 * 格式化字串上，去掉小数后面的0，数值0没有小数部分
	 * 方法本身不ROUND，超出指定小数位数的部分如果不是0也不移除
	 * @param d
	 * @param dec
	 * @param 是否保持0值的小数
	 * @return
	 */
	public static String getNoTailZeroString(double d, String dec){
		return getNoTailZeroString(d, dec, false);
	}
	
	   /**
		 * 格式化字串上，去掉小数后面的0
		 * 方法本身不ROUND，超出指定小数位数的部分如果不是0也不移除
		 * @param d
		 * @param dec
		 * @param 是否保持0值的小数
		 * @return
		 */
		public static String getNoTailZeroString(double d, String dec, boolean keepZeroDec){
			if(!keepZeroDec && Double.compare(d, 0D) == 0) return "0";
			String ret = String.format(_defaultFloatFmt, d);
			int decLen = 0;
			if( dec != null && dec.trim().length() > 0 && "INF".compareToIgnoreCase(dec.trim()) != 0 ){
				try{
					decLen = Integer.parseInt(dec);
				}catch(Exception err){
					decLen = 0;
				}
			}
			int pos = ret.indexOf(".");
			if( pos >= 0 ){
				int len = ret.length() -1;
				int lenDec = pos + decLen;
				int diff = len - pos;
				if( decLen > 0 && diff == decLen) return ret;
				if(decLen == 0 || decLen < diff){
					while( ret.charAt(len) == '0' && len > lenDec){
						len --;
					}
					if( ret.charAt(len) == '.'){
						len --;
					}
					ret = ret.substring(0, len + 1);
				}
				if( decLen > 0){
					diff = len - pos;
					// 已经没有小数点了
					if( diff < 0){
						ret += "." + ZERO_50.substring(0, decLen > 50 ? 50 : decLen);					
					}else if( diff < decLen ){
						diff = decLen - diff;
						ret += ZERO_50.substring(0, diff > 50 ? 50 : diff);	
					}
				}
			}else if(decLen > 0){
				ret += "." + ZERO_50.substring(0, decLen > 50 ? 50 : decLen);
			}
			return ret;
		}
}
